package com.zkca.xf.ui.activity.personprotect;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zkca.xf.ConstantsXF;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.DeviceLBean;
import com.zkca.xf.model.javabean.DeviceType;
import com.zkca.xf.model.javabean.uploadbean.RequestInspect;
import com.zkca.xf.presenter.DeviceAddPresenter;
import com.zkca.xf.presenter.DeviceListPresenter;
import com.zkca.xf.ui.adapter.RecycRadioAdapter;
import com.zkca.xf.ui.adapter.SingleAdapter;
import com.zkca.xf.ui.adapter.ViewHolder;
import com.zkca.xf.ui.customview.FlowLayoutManager;
import com.zkca.xf.ui.customview.XCRoundRectImageView;
import com.zkca.xf.utils.DisplayUtil;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.SpaceItemDecoration;
import com.zkca.xf.utils.StringUtils;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.DeviceAddView;
import com.zkca.xf.view.Device_LView;
import com.zkca.xf.view.OnRgitemChangeListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeviceListAct extends BaseTitleActivity implements View.OnClickListener, Device_LView, DeviceAddView {


    @BindView(R.id.device_list)
    XRecyclerView deviceList;
    @BindView(R.id.wushuju)
    ImageView wushuju;
    @BindView(R.id.xre_dtype)
    XRecyclerView xreDtype;
    @BindView(R.id.deviceadss)
    EditText deviceadss;
    @BindView(R.id.deviceanum)
    EditText deviceanum;
    @BindView(R.id.shaixuan_cancel)
    TextView shaixuanCancel;
    @BindView(R.id.shaixuan_sure)
    TextView shaixuanSure;
    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;


    private int type;
    private String edit = "edit";
    private DeviceListPresenter deviceListPresenter;
    private RequestInspect requestInspect;
    int pageNum = 1;
    int pageSize = 10;

    private LinearLayoutManager linearLayoutManager;
    private List<DeviceLBean.DataBean> dataBeanList = new ArrayList<>();
    private SingleAdapter<DeviceLBean.DataBean> adapter;

    private List<DeviceType.DataBean> devicTypelist = new ArrayList();
    private ArrayList<String> devicTypeNamelist = new ArrayList();
    private DeviceAddPresenter xunDianAddPresenter;
    RecycRadioAdapter recycRadioAdapter;
    private String devId = "", typeName = "", installPosition = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        ButterKnife.bind(this);
        initMyview();

        initAdapter();

        xunDianAddPresenter = new DeviceAddPresenter(this, this);
        getType();

        initDecType();

    }

    private void initDecType() {
        recycRadioAdapter = new RecycRadioAdapter(mContext, devicTypeNamelist);
        FlowLayoutManager flowLayoutManager = new FlowLayoutManager(mContext, true);
        xreDtype.setLayoutManager(flowLayoutManager);
        recycRadioAdapter.setOnRgitemChangeListenner(new OnRgitemChangeListener() {
            @Override
            public void onItemCheckChange(int i) {
                typeName = devicTypeNamelist.get(i);
                if (xreDtype.getScrollState() != RecyclerView.SCROLL_STATE_IDLE || (xreDtype.isComputingLayout() == false)) {
                    recycRadioAdapter.notifyDataSetChanged();
                }
            }
        });


        xreDtype.setAdapter(recycRadioAdapter);
    }


    private void getType() {
        RequestInspect requestInspectType = new RequestInspect();
        Map map = new HashMap<String, Object>();
        map.put("devId", "111111");
        requestInspectType.setParam(map);
        requestInspectType.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestInspectType.setAction(0);
        requestInspectType.setTimeStamp(TimeUtils.getTime());
        requestInspectType.setSign(MyApplication.getInstance().generateDvSign(requestInspectType));
        xunDianAddPresenter.getDvType(requestInspectType);
    }

    private void initAdapter() {
        adapter = new SingleAdapter<DeviceLBean.DataBean>(this, dataBeanList, R.layout.device_list_item) {
            @Override
            public void convert(ViewHolder holder, final DeviceLBean.DataBean dataBean, int position) {

                XCRoundRectImageView imageView = holder.getView(R.id.iv_device);
                TextView deviceName = holder.getView(R.id.device_name);
                TextView devicetype = holder.getView(R.id.device_type);
                TextView deviceId = holder.getView(R.id.device_id);
                TextView deviceAdress = holder.getView(R.id.device_address);//device_state
                TextView deviceState = holder.getView(R.id.device_state);

                String devImage1 = dataBean.getDevImage1();
                String devName = dataBean.getDevName();
                String devId = dataBean.getDevId();
                String typeName = dataBean.getTypeName();
                String installPosition = dataBean.getInstallPosition();
                int devStatus = dataBean.getDevStatus();

                if (devStatus == 0) {
                    deviceState.setText("安全");
                    deviceState.setTextColor(Color.rgb(52, 209, 78));
                } else {
                    deviceState.setText("故障");
                    deviceState.setTextColor(Color.rgb(216, 29, 29));
                }
//                RoundedCorners roundedCorners = new RoundedCorners(10);
//                RequestOptions requestOptions = new RequestOptions().placeholder(R.mipmap.app_name) //加载中图片
//                        .error(R.mipmap.zwf) //加载失败图片
//                        .centerCrop()
//                        .transform(roundedCorners) // 填充方式
////                 .override(600,600) //尺寸
////                 .transform(new CircleCrop()) //圆角
//
//                        .priority(Priority.HIGH) //优先级
//                        .diskCacheStrategy(DiskCacheStrategy.NONE); //缓存策略，后面详细介绍

                Glide.with(DeviceListAct.this).load(ConstantsXF.URL_SERVER_CE + devImage1).asBitmap().placeholder(R.mipmap.zwf).error(R.mipmap.zwf).into(imageView);
                deviceName.setText(devName);
                devicetype.setText(typeName);
                deviceAdress.setText(installPosition);
                deviceId.setText(devId);

                holder.setItemViewOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent(DeviceListAct.this, Device_XActivity.class);
                        intent.putExtra("databean", dataBean);
                        startActivity(intent);
                    }
                });

            }
        };
        deviceList.setAdapter(adapter);
    }


    private void initMyview() {
        setTitleText("巡点列表");
        setleftTextVisibility(true);
        setleftImgVisibility(true);

        deviceListPresenter = new DeviceListPresenter(this, this);
        initDvData(pageNum, devId, typeName, installPosition);
        linearLayoutManager = new LinearLayoutManager(mContext);
        deviceList.setLayoutManager(linearLayoutManager);
        deviceList.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dip2px(
                mContext, 0.5f)));
        deviceList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                deviceList.setLoadingMoreEnabled(true);
                dataBeanList.clear();
                pageNum = 1;
                initDvData(pageNum, devId, typeName, installPosition);
            }

            @Override
            public void onLoadMore() {
                pageNum++;
                initDvData(pageNum, devId, typeName, installPosition);
            }
        });

    }

    private void initDvData(int pagenum, String devId, String typeName, String installPosition) {
        HashMap map = new HashMap();
        if (!devId.equals("")){
            map.put("devId", devId);
        }
        if (!typeName.equals("")){
            map.put("typeName", typeName);
        }
        if (!installPosition.equals("")){
            map.put("installPosition", installPosition);
        }

        requestInspect = new RequestInspect();
        requestInspect.setParam(map);
        requestInspect.setPageNum(pagenum);
        requestInspect.setPageSize(pageSize);
        requestInspect.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestInspect.setAction(2);
        requestInspect.setTimeStamp(TimeUtils.getTime());
        requestInspect.setSign(MyApplication.getInstance().generateDvSign(requestInspect));
        deviceListPresenter.getDevicelist(requestInspect);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.re_search:
//                pullAprent.setVisibility(View.VISIBLE);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

                if (edit == null || edit.equals("")) {
                    ToastUtils.show(this, "请输入查询内容");
                } else if (type == 0) {
                    type = 2;
                } else {
//                    pullToRefreshListView.setVisibility(View.GONE);
//                    spinKit.setVisibility(View.VISIBLE);
//                    tvRemind.setVisibility(View.VISIBLE);
//                    getdata(type, edit);
                }
        }
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void getDev(DeviceLBean deviceLBean) {
        deviceList.refreshComplete();
        deviceList.loadMoreComplete();
        if (deviceLBean.getResult() == 0) {
            List<DeviceLBean.DataBean> data = deviceLBean.getData();
            dataBeanList.addAll(data);

            if (deviceLBean.getTotalpage() == pageNum) {
                deviceList.setLoadingMoreEnabled(false);
            }
            if (pageNum == 1 && data.size() == 0) {
                wushuju.setVisibility(View.VISIBLE);
            } else {
                wushuju.setVisibility(View.GONE);
            }
            adapter.notifyDataSetChanged();

        }
    }

    @Override
    public void getDvtype(DeviceType deviceType) {
        if (deviceType.getResult() == 0) {
            List<DeviceType.DataBean> data = deviceType.getData();
            devicTypelist.addAll(data);
            for (int i = 0; i < devicTypelist.size(); i++) {
                String typeName = devicTypelist.get(i).getTypeName();
                devicTypeNamelist.add(typeName);
                recycRadioAdapter.notifyDataSetChanged();
                LogUtil.e("设备类型：", typeName);
            }
        } else if (deviceType.getResult() == 9) {
            //  ToastUtils.show(this, deviseid + "设备已添加！");
            //  finish();
        }
    }

    @Override
    public void inPut(String s) {

    }

    @OnClick({R.id.shaixuan_cancel, R.id.shaixuan_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shaixuan_cancel:
                break;
            case R.id.shaixuan_sure:
                dataBeanList.clear();
                pageNum = 1;
                if (!StringUtils.isEmpty(deviceadss.getText())) {
                    installPosition = deviceadss.getText().toString();
                }
                if (!StringUtils.isEmpty(deviceanum.getText())) {
                    devId = deviceanum.getText().toString();
                }
                initDvData(1, devId, typeName, installPosition);
                drawerLayout.closeDrawers();
                break;
        }
    }
}
